package models;

import play.*;
import play.db.jpa.*;
import play.libs.Codec;

import javax.persistence.*;
import java.util.*;
import play.data.validation.*;

@Entity
public abstract class User extends Model {
	
	public String email;
	public String passwordHash;
	public String firstname;
	public String lastname;
	public Date dateOfBirth;
	public String street;
	public int streetNumber;
	public int zipcode;
	public String city;
	public String telephone;
	
	@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
	public List<Offer> offers;
	
	/**
	 * Minimal constructor, the password is stored as MD5-hash
	 * @param email The user's email address
	 * @param password The user's password
	 */
	public User(String email, String password) {
		this.email = email;
		//TODO: Maybe change hash to sha-1
		this.passwordHash = Codec.hexMD5(password);
		create();
	}
	
	/**
	 * Find the user with the given email address
	 * @param email The user's email address
	 * @return the user with the email address 'email'
	 */
    public static User findByEmail(String email) {
        return find("email", email).first();
    }
    
    /**
     * Check the password
     * @param password
     * @return
     */
    public boolean checkPassword(String password) {
        return passwordHash.equals(Codec.hexMD5(password));
    }

    /**
     * Check if a given email address is still available for registration
     * @param email
     * @return
     */
    public static boolean isEmailAvailable(String email) {
        return findByEmail(email) == null;
    }

    public boolean isAdmin() {
    	return (this instanceof Admin);
    }
    
    public abstract String hasClass();
    
}
